package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.base.response.JsonResult;
import cn.tedu.coolshark.mapper.UserMapper;
import cn.tedu.coolshark.pojo.dto.UserDTO;
import cn.tedu.coolshark.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import javax.swing.*;

import static cn.tedu.coolshark.base.response.StatusCode.PASSWORD_ERROR;
import static cn.tedu.coolshark.base.response.StatusCode.USER_NOT_EXIST;

@Slf4j
@RestController
@Api(tags = "用户模块管理")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    @ApiImplicitParam(name = "userDTO", value = "用户信息", required = true)
    public int login(@RequestBody UserDTO userDTO, @ApiIgnore HttpSession session) {
        UserVO userVO = userMapper.selectByUsername(userDTO.getUsername());
        if (userVO == null) {
            log.debug("用户不存在");
            return 3;
        }
        if (!userVO.getPassword().equals(userDTO.getPassword())) {
            log.debug("密码错误");
            return 2;
        }
        session.setAttribute("user", userVO);
        log.debug("登录成功");
        return 1;
    }

    @GetMapping("/currentUser")
    @ApiOperation(value = "获取当前用户信息")
    public UserVO getCurrentUser(@ApiIgnore HttpSession session) {
        return (UserVO) session.getAttribute("user");
    }

    @GetMapping("/logout")
    @ApiOperation(value = "退出登录")
    public void logout(@ApiIgnore HttpSession session) {
        session.removeAttribute("user");
    }
}
